package com.zzw.filter;

import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 校验token是否正确
 *
 * @Author: zhangzhiwei
 * @Date: 2022/4/7 22:15
 */
@Component
public class TokenFilter implements GlobalFilter {

    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // url白名单
    private static List<String> whiteUrl = new ArrayList<>();

    static {
        whiteUrl.add("/code/create");
        whiteUrl.add("/user/register");
        whiteUrl.add("/user/login");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取请求的url，如果在白名单就放行，否则校验token是否有效
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求url
        String path = request.getURI().getPath();
        for (String s : whiteUrl) {
            if(path.contains(s)){
                // 放行
                return chain.filter(exchange);
            }
        }
        // 从request对象中获取token
        String token = request.getCookies().get("token").get(0).getValue();
        // 拿着token去redis中查询，不存在的话就拒绝访问
        String redisToken = stringRedisTemplate.opsForValue().get(token);
        if(StringUtils.isBlank(redisToken)){
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            log.debug("=====>无效token，拒绝访问！");
            String data = "Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }
}
